package com.java.test.functional.designPatterm;

import java.util.List;
import java.util.function.Function;
import java.util.function.UnaryOperator;


public class ChainOfResponsibilityMain {

    public static void main(String[] args) {
        // java7
        ProcessingObject<String> p1 = new HeaderTextProcessing();

        ProcessingObject<String> p2 = new FooterTextProcessing();
        p1.setSuccessor(p2);
        String result1 = p1.handle("内容~~~~~~~~~~~~~~~~~~");
        System.out.println(result1);


        System.out.println();
        System.out.println();


        List<String> list=null;

        // java8
        UnaryOperator<String> headerProcessing =
                (String text) -> "<header>Java8</header>\n" + text;

        UnaryOperator<String> fotterProcessing =
                (String text) -> text+"\n<footer>Java8</footer>";

        Function<String, String> pipeline = headerProcessing.andThen(fotterProcessing);
        String result2 = pipeline.apply("内容*********************");
        System.out.println(result2);
    }

    static private abstract class ProcessingObject<T> {
        protected ProcessingObject<T> successor;

        public void setSuccessor(ProcessingObject<T> successor) {
            this.successor = successor;
        }

        public T handle(T input) {
            T r = handleWork(input);
            if (successor != null) {
                return successor.handle(r);
            }
            return r;
        }

        abstract protected T handleWork(T input);
    }

    static private class HeaderTextProcessing
            extends ProcessingObject<String> {
        public String handleWork(String text) {
            return "<header>java7</header>\n" + text;
        }
    }

    static private class FooterTextProcessing
            extends ProcessingObject<String> {
        public String handleWork(String text) {
            return text+"\n<footer>java7</footer>" ;
        }
    }
}


